#include "bsp_delay.h"
#include "bsp_int.h"
#include "bsp_led.h"

/* 延时初始化函数 */
void delay_init(void)
{
	GPT1->CR = 0;

	GPT1->CR = 1 << 15; /* 设置软复位 */
	while (GPT1->CR >> 15 & 0x1)
		;

	GPT1->CR |= (1 << 1) | (1 << 6); /* 设置GPT1时钟源为ipg1_clk为66M */
	GPT1->PR = 65 << 0;				 /* 设置为66分频 */
	GPT1->OCR[0] = 0xffffffff;		 /* 计数约等于75分钟 */
	GPT1->CR |= (1 << 0);			 /* 使能GPT1中断 */
}

/* 微秒延时 */
void delay_us(volatile unsigned int usdelay)
{
	unsigned long oldcnt, newcnt;
	unsigned long tcntvalue = 0;
	oldcnt = GPT1->CNT;
	while (1)
	{
		newcnt = GPT1->CNT;
		if (newcnt != oldcnt)
		{
			if (newcnt > oldcnt)
			{
				tcntvalue += newcnt - oldcnt;
			}
			else
			{
				tcntvalue += 0xffffffff - oldcnt + newcnt;
			}
			oldcnt = newcnt;
			if(tcntvalue >= usdelay)
			{
				break;
			}

		}
	}
}

/* 毫秒延时 */
void delay_ms( unsigned int msdelay)
{
	int i = 0;
	for(i=0; i<msdelay ;i++)
	{
		delay_us(1000);
	}
}
